package org.isouland.cpwx.api.base;


import org.isouland.cpwx.api.common.AccessToken;
import org.isouland.cpwx.api.core.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class WxAccessTokenAPI {
	
	private static final Logger logger = LoggerFactory.getLogger(WxAccessTokenAPI.class);

	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";  
	
	public static AccessToken getAccessToken(String appId, String secret) {  
	    AccessToken accessToken = null;  
	    String requestUrl = access_token_url.replace("APPID", appId).replace("APPSECRET", secret);
	    JSONObject jsonObject = HttpUtil.sendGet(requestUrl);
	    if (null != jsonObject) {  
	        try {  
	            accessToken = new AccessToken();  
	            accessToken.setAccesstoken(jsonObject.getString("access_token"));  
	            accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
	            logger.info("[ACCESSTOKEN]", "获取ACCESSTOKEN成功:{}", new Object[]{accessToken});
	        } catch (Exception e) {  
	            accessToken = null;  
	            // 获取token失败  
	            int errcode = jsonObject.getIntValue("errcode");
	            String errmsg = jsonObject.getString("errmsg");
	            logger.info("[ACCESSTOKEN]", "获取ACCESSTOKEN失败 errcode:{} errmsg:{}", new Object[]{errcode,errmsg});
	        }  
	    }  
	    return accessToken;  
	}
	 
}
